const router = require("koa-router")();

router.prefix("/mono");

const PagerHelper = require("./PagerHelper");

var client = require("../db/momo/MonoDb");

router.get("/init", async (ctx, next) => {
  var result = await new Promise((resolve, reject) => {
    client
      .connect(function (err) {
        if (err) throw err;
        var dbo = client.db("runoob");

        dbo
          .createCollection("abc")
          .then((res) => {
            resolve("已创建集合");
          })
          .catch((err) => {})
          .finally(() => {
            client.close();
          });
      })
      .catch((err) => {
        console.log("数据库连接失败");
      });
  });

  ctx.body = PagerHelper.SuccessRes(result);
});

router.get("/", async (ctx, next) => {
  var result = await new Promise((resolve, reject) => {
    client.connect(function (err) {
      if (err) throw err;
      var dbo = client.db("runoob");
      var q = {};

      dbo
        .collection("site")
        .find(q)
        .toArray((err, docs) => {
          // client.close();
          resolve(docs);
          
        });
    });
  });

  ctx.body = PagerHelper.SuccessRes(result);
});

router.get("/save", async (ctx, next) => {
  var result = await new Promise((resolve, reject) => {
    client.connect(function (err) {
      if (err) throw err;
      var dbo = client.db("runoob");
      var entity = { name: "菜鸟教程", url: "www.runoob" };

      dbo.collection("site").insertOne(entity, function (err, res) {
        if (err) throw reject(err);
        console.log("文档插入成功");
        client.close();
        resolve(res);
      });
    });
  });

  ctx.body = PagerHelper.SuccessRes(result.ops);
});

router.get("/update", async (ctx, next) => {
  var result = await new Promise((resolve, reject) => {
    client.connect(function (err) {
      if (err) throw err;
      var dbo = client.db("runoob");
      var entity = { name: "菜鸟222222222222教程" };

      dbo
        .collection("site")
        .updateOne(
          entity,
          { $set: { url: "www.runoob333333333" } },
          function (err, res) {
            if (err) throw reject(err);
            console.log("文档插入成功");
            client.close();
            resolve(res);
          }
        );
    });
  });

  ctx.body = PagerHelper.SuccessRes(result);
});

module.exports = router;
